package cn.funnymap.lgis.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.intellij.lang.annotations.Flow;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author wenzf
 * @since 2025/10/21 10:06
 */
public class NumberScale2Serializer extends JsonSerializer<Number> {
	private static final int SCALE = 2;
	private static final RoundingMode ROUNDING = RoundingMode.HALF_UP;
	
	@Override
	public void serialize(Number value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
		if (value == null) {
            // 如果值为 null，则写入 0
			jsonGenerator.writeNumber(0);
		} else if (value instanceof BigDecimal) {
			jsonGenerator.writeNumber(((BigDecimal) value).setScale(SCALE, ROUNDING));
		} else if (value instanceof Double) {
			jsonGenerator.writeNumber(BigDecimal.valueOf((Double) value).setScale(SCALE, ROUNDING));
		} else if (value instanceof Float) {
			jsonGenerator.writeNumber(BigDecimal.valueOf((Float) value).setScale(SCALE, ROUNDING));
		} else if (value instanceof Integer) {
			jsonGenerator.writeNumber((Integer) value);
		} else if (value instanceof Long) {
			jsonGenerator.writeNumber((Long) value);
		} else {
			jsonGenerator.writeNumber(value.toString());
		}
	}
}
